#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "rawparser.h"
#include <QString>
#include <stdio.h>
#include <string.h>
#include <QFileDialog>
#include <QDebug>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/highgui/highgui_c.h>
#include <opencv2/opencv.hpp>
#include <cassert>
#include <string>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <sstream>
#include "json11.hpp"
#include<regex>
#include <fstream>
#include "doo.h"
#include <QCoreApplication>
#include <math.h>
#include <windows.h>
#include "atlstr.h"
#include<QChartView>
#include <iostream>
#include <fstream>

using namespace json11;
using std::string;
using namespace std;
using namespace cv;
QString fold_pathf;
string jsonfp,dd;


//string command = "dji_irp.exe -s DJI_0984.JPG -a measure -o hhh.raw";
//system(command.c_str());

#define _TRACK
#ifdef _TRACK

__inline VOID _Track(LPCTSTR ptzFormat, ...)
{
    va_list vlArgs;
    TCHAR tzText[1024];
    va_start(vlArgs, ptzFormat);
    wvsprintf(tzText, ptzFormat, vlArgs);
    OutputDebugString(tzText);
    va_end(vlArgs);
}

#ifdef __FUNCTION__
#define _TrackSpot()		_Track(TEXT("Track in %s.\n"), TEXT(__FUNCTION__));
#else // __FUNCTION__
#define _TrackSpot()		_Track(TEXT("Track in %s. Line %u.\n"), TEXT(__FILE__), __LINE__)
#endif // __FUNCTION__

#define _TrackElapse(e)		{DWORD d = GetTickCount(); e; _Track(TEXT("Track %s: Elapse %u ms.\n"), TEXT(#e), GetTickCount() - d);}

#else // _TRACK

#pragma warning(disable:4353)
#define _Track				((VOID) (0))
#define _TrackSpot()
#define _TrackElapse(e)		((VOID) (e))

#endif // _TRACK





MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{

    ui->setupUi(this);
    connect(ui->gene,SIGNAL(clicked(bool)),this,SLOT(gene()));
	connect(ui->geneTempDiffer, SIGNAL(clicked(bool)), this, SLOT(geneTempDiffer()));
    connect(ui->loadpic,SIGNAL(clicked(bool)),this,SLOT(loadpic()));
}

// 生成曲线
void MainWindow::gene()
{
    const char* fp = "1.raw";
    RawParser PIC(fp,width,height);
    QChart* chart = new QChart();
    chart->setTitle("温度曲线"); //设置标题
	QValueAxis *xAxis = new QValueAxis();
	xAxis->setLabelFormat("%d");
    PIC.preloadRaw();
	std::vector<QColor> colors = {QColor(255,0,0), QColor(0,255,0), QColor(0,0,255)};
	_temp.clear();
    for(int j =0;j<cc.size();j++)   //cc:线的条数
	{
		std::vector<float> t;
		QLineSeries *series = new QLineSeries();
		QScatterSeries *scatterSeries = new QScatterSeries();
		scatterSeries->setMarkerSize(8);
        for(int i = 0;i<cc[j].size();i=i+2){
            int tem=0;
            if(PIC.getPointTemperature(cc[j][i],cc[j][i+1],tem)){
				t.push_back(tem / 10.0);
                series->append(i / 2 + 1, tem/10.0);
				series->setColor(colors[j % 3]);
				scatterSeries->setColor(colors[j % 3]);
				scatterSeries->append(i / 2 + 1, tem / 10.0f);
            }
        }
		_temp.push_back(t);
		chart->addSeries(series);  
		chart->addSeries(scatterSeries);
    }
	chart->createDefaultAxes();
	QChartView *view = new QChartView(chart);
	QPixmap p = view->grab();
	QImage image = p.toImage();
	image.save("chart1.png");
	//ui->widget->setChart(chart);
}


void MainWindow::geneTempDiffer()
{
	const char* fp = "1.raw";
	RawParser PIC(fp, width, height);
	QChart* chart = new QChart();
	chart->setTitle("温差曲线"); //设置标题
	QValueAxis *xAxis = new QValueAxis();
	xAxis->setLabelFormat("%d");
	PIC.preloadRaw();
	std::vector<QColor> colors = { QColor(255,0,0), QColor(0,255,0), QColor(0,0,255) };

	String s = "";
	String qs = "结论:存在异常的绝缘子编号:";
	_temp_diff.clear();

	//for (int j = 0; j < cc.size(); j++)
	for (int j = 0; j < _temp.size(); j++)
	{
		std::vector<float> diff;
		QLineSeries *series = new QLineSeries();
		QScatterSeries *scatterSeries = new QScatterSeries();
		scatterSeries->setMarkerSize(8);

		//for (int i = 0; i < cc[j].size(); i = i + 2) {
		for (int i = 1; i < _temp[j].size() - 1; i = i + 1) {
			float dn = 0;
			dn = fabs((_temp[j][i - 1] + _temp[j][i+1]) / 2 - _temp[j][i]);
			diff.push_back(dn);
			if (dn > 2) {
				//s = QString::number(i);
				string s = to_string(i);
				qs.append(s);
				qs.append(" ; ");
			}
			series->append(i, dn);
			series->setColor(colors[j % 3]);
			scatterSeries->setColor(colors[j % 3]);
			scatterSeries->append(i, dn );		
		}
		_temp_diff.push_back(diff);
		chart->addSeries(series);
		chart->addSeries(scatterSeries);
	}
	   
	if (qs == "结论:存在异常的绝缘子编号:") {

		ofstream os;     //创建一个文件输出流对象
		os.open("out.txt");//将对象与文件关联
		string str = "结论：正常";
		cin >> str;
		os << str;   //将输入的内容放入txt文件中
		os.close();

		//ui->mylabel->setText(" 结论：正常");

	}
	else 
	{    
		ofstream os;     //创建一个文件输出流对象
		os.open("out.txt");//将对象与文件关联
		cin >> qs;
		os << qs;   //将输入的内容放入txt文件中
		os.close();
		
		//ui->mylabel->setText(qs);
	}	    
		chart->createDefaultAxes();
		QChartView *view=new QChartView (chart);
		QPixmap p = view->grab();
		QImage image = p.toImage();
		
		//json_fileName = json_fileName.substr(0, json_fileName.length() - 3) + "png";
		image.save("chart2.png");
		//ui->widget_2->setChart(chart);
}
void MainWindow::load()
{
    //QString fold_path = QFileDialog::getExistingDirectory(this, "please", "/");
    //if(fold_path.isEmpty()){
    //    return;
    //}
    //fold_pathf = fold_path;
}

void MainWindow::loadpic()
{
    //int a[10][2]={{192,177},{185,227},{216,181},{207,229},{235,180},{227,230},{256,183},{250,235},{283,183},{274,235}};
    QString file_path = QFileDialog::getOpenFileName(this, "请选择红外图片",".","图片文件(*.jpg *.png *.JPG)" );

    if(file_path.isEmpty())
    { 
		return; 
	}
    QFileInfo fileinfo = QFileInfo(file_path);
    QString ffp = fileinfo.absoluteFilePath();
    QString ffpn = fileinfo.absoluteDir().path();
	fold_pathf = ffpn;
	//json_fileName = file_path.toStdString();
	//json_fileName = json_fileName.substr(0, json_fileName.length() - 3) + "json";
    //string filename = name.toStdString();
	QTextCodec *code = QTextCodec::codecForName("GB2312");//解决中文路径问题
	json_fileName = code->fromUnicode(file_path).data();

	/* json_fileName = file_path.toStdString();*/
	json_fileName = json_fileName.substr(0, json_fileName.length() - 3) + "json";
	//string filename = name.toStdString();
	string fps = ffpn.toStdString(); //不包含文件名
	std::string fp = code->fromUnicode(ffp).data();
	//string fp = ffp.toStdString(); //包含文件名


    string command = "dji_irp.exe -s "+fp+" -a measure -o 1.raw";
    WinExec(command.c_str(), SW_HIDE);
    
	string command_alg = "out_split.exe " + fp;

	AllocConsole();
	ShowWindow(GetConsoleWindow(), SW_HIDE);
	system(command_alg.c_str());
	
		
	loadjson();
    //String path;
    //path = file_path.toStdString();
    Mat oimg = imread(fp);
	width = oimg.cols;
	height = oimg.rows;
	std::vector<Scalar> colors = { Scalar(0,0,255) ,Scalar(0,255,0) ,Scalar(255,0,0) };
	for (int j = 0; j < cc.size(); j++)
	{
		for(int i = 0;i< cc[j].size();i=i+2)
		{
			//rectangle(oimg,Point(cc[j][i]-5,cc[j][i+1]-5),Point(cc[j][i]+5,cc[j][i+1]+5),colors[j %3],1);
			circle(oimg, Point(cc[j][i], cc[j][i + 1]), 3, colors[j % 3], -1);
		}
	}
    cvtColor(oimg,oimg,CV_BGR2RGB);
    QImage img1 = QImage(static_cast<uchar *>(oimg.data),oimg.cols,oimg.rows,QImage::Format_RGB888);
    ui->piclabel->setPixmap(QPixmap::fromImage(img1));

}

// 读json文件，输出坐标点，支持多串绝缘子坐标的输出
int parse_json_file(std::string json_file, std::vector<std::vector<float> > &pp)
{
	std::ifstream myfile(json_file);
	std::string str((std::istreambuf_iterator<char>(myfile)),
		std::istreambuf_iterator<char>());
	string err;
	const auto json = Json::parse(str, err);
	pp.clear();
	for (auto& k : json["shapes"].array_items())
	{
		std::vector<float> vf;
		std::cout << "shape:" << std::endl;
		for (auto& p : k["points"].array_items())
		{
			vf.push_back(atof(p[0].dump().c_str()));
			vf.push_back(atof(p[1].dump().c_str()));
		}
		pp.push_back(vf);
	}
	return 1;
}


void MainWindow::loadjson()
{	
    //jsonfp = json_fileName;
    //dd =readjs(jsonfp);
    //cc = pipei(dd);
	parse_json_file(json_fileName, cc);
    //qDebug() << cc;
}



MainWindow::~MainWindow()
{
    delete ui;
}
